<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col
          ><el-button type="primary" @click="addRolesDialog = true"
            >添加角色</el-button
          ></el-col
        >
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="[
                'row-bottom',
                'colcenter',
                index1 === 0 ? 'row-top' : '',
              ]"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="['colcenter', index2 === 0 ? '' : 'row-top']"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6"
                    ><el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i
                  ></el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addRolesDialog"
      width="40%"
      @close="roleDialogClose"
    >
      <!-- 表单区域 -->
      <el-form
        ref="addRolesRef"
        :model="addRolesList"
        label-width="80px"
        :rules="addRolesRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRolesBtn">确 定</el-button>
        <el-button @click="addRolesDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editRolesDialog"
      width="40%"
      @close="editRolesDialogClose"
    >
      <el-form
        ref="editRolesRef"
        :model="editRolesList"
        label-width="80px"
        :rules="editRolesRulers"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editRolesDialogBtn">确 定</el-button>
        <el-button @click="editRolesDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="addRightsDialog"
      width="40%"
      @close="setRightsDialogClose"
    >
      <el-tree
        ref="setRightsRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        :default-checked-keys="defKeys"
        node-key="id"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRightsDialog = false">取 消</el-button>
        <el-button type="primary" @click="setRightsCommit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addRolesDialog: false,
      // 添加角色列表
      addRolesList: {
        roleName: "",
        roleDesc: "",
      },
      // 添加角色规则
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      editRolesDialog: false,
      // 编辑角色列表
      editRolesList: {
        id: "",
        roleName: "",
        roleDesc: "",
      },
      // 编辑角色规则
      editRolesRulers: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      addRightsDialog: false,
      // 权限数据
      rightsList: [],
      // 树形控件的树形绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 默认勾选的节点id值
      defKeys: [],
      // 当前要分配权限的角色的id
      currenRoleId: "",
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表数据失败");
      this.rolesList = res.data;
    },
    // 监听添加角色对话框关闭
    roleDialogClose() {
      this.$refs.addRolesRef.resetFields();
    },
    // 监听添加用户按钮的操作
    addRolesBtn() {
      this.$refs.addRolesRef.validate(async (value) => {
        if (!value) return this.$message.error("请输入正确信息并提交");
        // 发送添加角色网络请求
        const { data: res } = await this.$http.post("roles", this.addRolesList);
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.getRolesList();
        this.addRolesDialog = false;
        return this.$message.success("添加用户成功");
      });
    },
    // 监听删除用户按钮的操作
    async deleteRoles(id) {
      const a = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (a !== "confirm") return this.$message.info("已取消删除");
      // 发送删除用户的请求
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除角色失败");
      this.getRolesList();
      return this.$message.success("成功删除");
    },
    // 监听编辑用户对话框关闭
    editRolesDialogClose() {
      this.$refs.editRolesRef.resetFields();
    },
    // 监听编辑用户按钮的操作
    async editRoles(id) {
      this.editRolesDialog = true;
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) returnthis.$message.error("获取数据失败");
      this.editRolesList.roleName = res.data.roleName;
      this.editRolesList.roleDesc = res.data.roleDesc;
      this.editRolesList.id = res.data.roleId;
      return;
    },
    // 编辑用户信息并提交
    editRolesDialogBtn() {
      this.$refs.editRolesRef.validate(async (value) => {
        if (!value) return this.$message.error("请正确填写信息");
        const { data: res } = await this.$http.put(
          "roles/" + this.editRolesList.id,
          {
            roleName: this.editRolesList.roleName,
            roleDesc: this.editRolesList.roleDesc,
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("修改角色数据失败");
        this.getRolesList();
        this.editRolesDialog = false;
        return this.$message.success("修改角色数据成功");
      });
    },
    // 根据id删除角色对应权限
    async removeRightById(role, rightId) {
      const a = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (a !== "confirm") return this.$message.info("取消了删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.message.error("删除权限失败");
      this.$message.success("权限删除成功");
      role.children = res.data;
    },
    // 分配权限的对话框
    async showSetRightDialog(role) {
      this.addRightsDialog = true;
      // 获取所有权限数据
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      this.rightsList = res.data;
      // 递归获取三级节点
      this.getLeafKeys(role, this.defKeys);
      this.currenRoleId = role.id;
    },
    // 通过递归形式，获取角色下所有三级权限的id，并保存到defKeys数组中
    getLeafKeys(node, arr) {
      // 如果node没有children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 监听分配权限对话框关闭
    setRightsDialogClose() {
      this.defKeys = [];
    },
    // 提交分配角色对话框里的信息
    async setRightsCommit() {
      this.addRightsDialog = false;
      const dataId = [
        ...this.$refs.setRightsRef.getCheckedKeys(),
        ...this.$refs.setRightsRef.getHalfCheckedKeys(),
      ];
      const idStr = dataId.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.currenRoleId}/rights`,
        {
          rids: idStr,
        }
      );
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("更新角色权限成功");
      this.$message.success("更新角色权限失败");
      this, this.getRolesList();
    },
  },
};
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.row-top {
  border-top: 1px solid #eee;
}
.row-bottom {
  border-bottom: 1px solid #eee;
}
.colcenter {
  display: flex;
  align-items: center;
}
</style>
